package com.dingup.homework.service.impl;

import com.alibaba.fastjson.JSON;
import com.dingup.homework.bean.DO.HwHomeworkDO;
import com.dingup.homework.bean.DO.HwHomeworkRecordDO;
import com.dingup.homework.bean.DO.HwSsatWordRecordDO;
import com.dingup.homework.bean.DTO.HomeworkProgressDTO;
import com.dingup.homework.bean.DTO.HomeworkRecordDODataMapInfo;
import com.dingup.homework.bean.HomeworkAnswerItem;
import com.dingup.homework.bean.HomeworkQuestion;
import com.dingup.homework.dao.HwHomeworkMapper;
import com.dingup.homework.dao.HwHomeworkRecordsMapper;
import com.dingup.homework.dao.HwSsatWordRecordMapper;
import com.dingup.homework.enums.HomeworkRecordStatusEnum;
import com.dingup.homework.enums.QuestionTypeEnum;
import com.dingup.homework.service.HwHomeworkRecordsService;
import com.dingup.homework.service.SendMsgService;
import com.dingup.homework.service.TeacherCorrectService;
import com.suyeer.basic.util.BLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author jun 2018/11/13.
 */
@Service
public class HwHomeworkRecordsServiceImpl implements HwHomeworkRecordsService {

    private final static Logger logger = LoggerFactory.getLogger(HwHomeworkRecordsServiceImpl.class);

    @Autowired
    private HwHomeworkRecordsMapper hwHomeworkRecordsMapper;

    @Autowired
    private HwSsatWordRecordMapper hwSsatWordRecordMapper;

    @Autowired
    private HwHomeworkMapper hwHomeworkMapper;

    @Autowired
    private TeacherCorrectService teacherCorrectService;

    @Autowired
    private SendMsgService sendMsgService;
    @Override
    @Transactional
    public Boolean add(HwHomeworkRecordDO hwHomeworkRecord) throws Exception {
        Boolean res = hwHomeworkRecordsMapper.add(hwHomeworkRecord);
        logger.info("保存学生record hwHomeworkRecord={}", JSON.toJSON(hwHomeworkRecord));
        teacherCorrectService.insert(hwHomeworkRecord.getId(), null, null);
        logger.info("保存批改记录 homeworkRecordId={}", hwHomeworkRecord.getId());
        return res;
    }

    @Override
    public Boolean update(HwHomeworkRecordDO hwHomeworkRecord) {
        return hwHomeworkRecordsMapper.update(hwHomeworkRecord);
    }

    @Override
    public HomeworkRecordDODataMapInfo getById(Integer id) {
        return hwHomeworkRecordsMapper.getById(id);
    }

    @Override
    public List<HomeworkRecordDODataMapInfo> listByStudentId(String userId) {
        return hwHomeworkRecordsMapper.listByStudentId(userId);
    }

    @Override
    public List<HomeworkRecordDODataMapInfo> listByUserIds(HashMap<String, Object> param) {
        return hwHomeworkRecordsMapper.listByUserIds(param);
    }

    @Override
    public Boolean exist(Integer homeworkId, String studentId) {
        return hwHomeworkRecordsMapper.exist(homeworkId, studentId);
    }

    @Override
    public List<HomeworkRecordDODataMapInfo> listByHomeworkId(Integer homeworkId) {
        return hwHomeworkRecordsMapper.listByHomeworkId(homeworkId);
    }

    @Override
    public List<HwHomeworkRecordDO> getList4WeekReport() {
        return hwHomeworkRecordsMapper.getList4WeekReport();
    }

    @Override
    public List<HwHomeworkRecordDO> getHomeworkSortResult(Integer homeworkId) {
        return hwHomeworkRecordsMapper.getHomeworkSortResult(homeworkId);
    }

    @Override
    public HwHomeworkRecordDO getByHomeworkAndStudent(Integer homeworkId, String studentId) {
        return hwHomeworkRecordsMapper.getByHomeworkAndStudent(homeworkId, studentId);
    }

    @Override
    public Boolean updateHomeworkValid(Integer id, Integer ifValidForStudent, Integer ifValidForTeacher) {
        return hwHomeworkRecordsMapper.updateHomeworkValid(id, ifValidForStudent, ifValidForTeacher);
    }

    @Override
    public List<HwHomeworkRecordDO> getByCreateTeacherId(String teacherId) {
        return hwHomeworkRecordsMapper.getByCreateTeacherId(teacherId);
    }

    @Override
    public void addHomeworkRecord(HwHomeworkDO hwHomework) throws Exception {
        for (String sId : hwHomework.getStudentIds()) {
            if (!exist(hwHomework.getId(), sId)) {
                HwHomeworkRecordDO thr = new HwHomeworkRecordDO();
                thr.setHomeworkId(hwHomework.getId());
                thr.setStudentId(sId);
                thr.setStatus(HomeworkRecordStatusEnum.WAITING);
                thr.setExpiredTime(hwHomework.getExpiredTime());
                thr.setTotalQuestion(hwHomework.getQuestionList().size());
                thr.setProgress(0);
                if (!add(thr)) {
                    throw new Exception(
                            String.format("给学生[%s]分发作业[%s]记录时失败.", sId, hwHomework.getId())
                    );
                }
                sendMsgService.sendHomeworkMsgWhenAssignHomework(sId, hwHomework.getHomeworkName(), hwHomework.getExpiredTime());
            }
        }
    }

    @Override
    public List<HomeworkProgressDTO> listProgress(Integer homeworkId) {
        return hwHomeworkRecordsMapper.listProgress(homeworkId);
    }

    @Override
    public void saveHomeworkProgress(Integer homeworkRecordId, Integer questionNum, Integer id, String examId,
                                     Integer correct, Integer total) {
        try {
            HwHomeworkRecordDO hwHomeworkRecord = getById(homeworkRecordId);
            if (hwHomeworkRecord == null) {
                throw new Exception("获取作业记录失败!");
            }
            if (questionNum < hwHomeworkRecord.getProgress()) {
                throw new Exception("作业进度数据无效!");
            }
            HwHomeworkDO hwHomework = hwHomeworkMapper.getById(hwHomeworkRecord.getHomeworkId());
            HomeworkQuestion homeworkQuestion = hwHomework.getQuestionList().get(questionNum - 1);
            String userId = hwHomeworkRecord.getStudentId();
            hwHomeworkRecord.setProgress(questionNum);
            List<HomeworkAnswerItem> answerItemList = hwHomeworkRecord.getAnswerData();
            if (answerItemList == null) {
                answerItemList = new ArrayList<>();
            }
            QuestionTypeEnum questionTypeEnum = homeworkQuestion.getQuestionType();
            HomeworkAnswerItem homeworkAnswerItem = null;
            if (questionTypeEnum == QuestionTypeEnum.SSAT) {
                HwSsatWordRecordDO ssatWordRecord = hwSsatWordRecordMapper.getByHomeworkInfo(userId, homeworkRecordId, questionNum);
                if (ssatWordRecord != null) {
                    homeworkAnswerItem = new HomeworkAnswerItem(questionNum, QuestionTypeEnum.SSAT,
                            ssatWordRecord.getTotalNum(), ssatWordRecord.getCorrectNum());
                }
            } else {
                homeworkAnswerItem = new HomeworkAnswerItem(questionNum, questionTypeEnum, id, examId, total, correct);
            }
            if (answerItemList.size() < questionNum) {
                answerItemList.add(homeworkAnswerItem);
            } else {
                answerItemList.set(questionNum - 1, homeworkAnswerItem);
            }
            hwHomeworkRecord.setAnswerData(answerItemList);
            if (!update(hwHomeworkRecord)) {
                throw new Exception("保存数据失败!");
            }
        } catch (Exception e) {
            BLogUtil.error(e);
        }

    }

    @Override
    public Integer getHomeworkIdByHomeworkRecordId(Integer homeworkRecordId) {
        HomeworkRecordDODataMapInfo hwHomeworkRecordDO = hwHomeworkRecordsMapper.getById(homeworkRecordId);
        if (hwHomeworkRecordDO != null) {
            return hwHomeworkRecordDO.getHomeworkId();
        }
        return null;
    }
}
